/// 预定义的盐值数组，用于哈希函数的混合计算
const SALTS: [u32; 64] = [
    0x1953c322, 0x588ccf17, 0x64bf600c, 0xa6be3f3d,
    0x341a02ea, 0x15b03217, 0x3b062858, 0x5956fd06,
    0x18b5624f, 0xe3be0b46, 0x20ffcd5c, 0xa35dfd2b,
    0x1fc4a9bf, 0x57c45d5c, 0xa8661c4a, 0x4f1b74d2,
    0x5a6dde13, 0x3b18dac6, 0x05a8afbf, 0xbbda2fe2,
    0xa2520d78, 0xe7934849, 0xd541bc75, 0x09a55b57,
    0x9b345ae2, 0xfc2d26af, 0x38679cef, 0x81bd1e0d,
    0x654681ae, 0x4b3d87ad, 0xd5ff10fb, 0x23b32f67,
    0xafc7e366, 0xdd955ead, 0xe7c34b1c, 0xfeace0a6,
    0xeb16f09d, 0x3c57a72d, 0x2c8294c5, 0xba92662a,
    0xcd5b2d14, 0x743936c8, 0x2489beff, 0xc6c56e00,
    0x74a4f606, 0xb244a94a, 0x5edfc423, 0xf1901934,
    0x24af7691, 0xf6c98b25, 0xea25af46, 0x76d5f2e6,
    0x5e33cdf2, 0x445eb357, 0x88556bd2, 0x70d1da7a,
    0x54449368, 0x381020bc, 0x1c0520bf, 0xf7e44942,
    0xa27e2a58, 0x66866fc5, 0x12519ce7, 0x437a8456,
];

/// 哈希函数类型定义，用于计算元素的哈希值
pub type HashFunc<T> = fn(data: &T) -> u32;

/// 布隆过滤器核心数据结构，用于高效集合成员检测
///
/// 包含哈希函数、位数组存储、表大小和哈希函数数量
#[derive(Debug, Clone, PartialEq)]
pub struct BloomFilter<T: ?Sized> {
    hash_func: HashFunc<T>,
    table: Vec<u8>,
    table_size: usize,
    num_functions: usize,
}

impl<T: ?Sized> BloomFilter<T> {
    /// 查询元素是否可能存在于布隆过滤器
    ///
    /// # 参数
    /// - `data`: 待查询元素的不可变引用
    ///
    /// # 返回值
    /// 返回`true`表示元素可能存在（可能存在误判），
    /// 返回`false`表示元素绝对不存在
    pub fn query(&self, data: &T) -> bool {
        let hash = (self.hash_func)(data);
        
        (0..self.num_functions).all(|i| {
            let subhash = hash ^ SALTS[i];
            let index = (subhash as usize) % self.table_size;
            let byte = self.table.get(index / 8).copied().unwrap_or(0);
            let bit_mask = 1 << (index % 8);
            (byte & bit_mask) != 0
        })
    }
    ///
    /// # 参数
    /// - `dest`: 目标缓冲区，必须至少有 `(table_size +7)/8` 字节容量
    ///
    /// # 错误
    /// 当目标缓冲区长度不足时返回 Err
    pub fn read(&self, dest: &mut [u8]) -> Result<(), &'static str> {
        let required_size = (self.table_size + 7) / 8;
        
        if dest.len() < required_size {
            return Err("Destination buffer too small");
        }
        
        dest[..required_size].copy_from_slice(&self.table[..required_size]);
        Ok(())
    }

    pub fn insert(&mut self, data: &T) {
        let hash = (self.hash_func)(data);
        
        for i in 0..self.num_functions {
            let subhash = hash ^ SALTS[i];
            let index = (subhash as usize) % self.table_size;
            let byte_index = index / 8;
            let bit_index = index % 8;
            
            self.table[byte_index] |= 1u8 << bit_index;
        }
    }

    /// 创建新的布隆过滤器实例
    ///
    /// # 参数
    /// - `table_size`: 位数组的理论大小（位数量）
    /// - `hash_func`: 基础哈希函数
    /// - `num_functions`: 实际使用的哈希函数数量
    ///
    /// # 错误
    /// 当哈希函数数量超过预定义盐值数量时返回 Err
    pub fn new(
        table_size: usize,
        hash_func: HashFunc<T>,
        num_functions: usize,
    ) -> Result<Self, &'static str> {
        if num_functions > SALTS.len() {
            return Err("Number of functions exceeds available salts");
        }

        let bytes = (table_size + 7) / 8;
        Ok(Self {
            hash_func,
            table: vec![0u8; bytes],
            table_size,
            num_functions,
        })
    }
    /// 从字节数组加载布隆过滤器的位数组数据
    ///
    /// # 参数
    /// - `source`: 源数据缓冲区，必须至少有 `table` 的字节长度
    ///
    /// # 错误
    /// 当源缓冲区长度不足时返回 Err
    pub fn load(&mut self, source: &[u8]) -> Result<(), &'static str> {
        let required_size = self.table.len();
        if source.len() < required_size {
            return Err("Source buffer too small");
        }
        self.table.copy_from_slice(&source[..required_size]);
        Ok(())
    }
    // 删除重复的函数定义参数列表和实现
    /// 
    /// # 返回值
    /// 返回 `Ok(Self)` 表示成功创建交集过滤器，
    /// 返回 `Err` 表示过滤器参数不兼容或内存分配失败
    pub fn intersection(
        filter1: &Self,
        filter2: &Self
    ) -> Result<Self, &'static str> {
        if filter1.table_size != filter2.table_size
            || filter1.num_functions != filter2.num_functions
            || filter1.hash_func as usize != filter2.hash_func as usize
        {
            return Err("Incompatible Bloom filters");
        }

        let mut result = BloomFilter::new(
            filter1.table_size,
            filter1.hash_func,
            filter1.num_functions,
        )?;

        result.table = filter1.table
            .iter()
            .zip(filter2.table.iter())
            .map(|(a, b)| a & b)
            .collect();

        Ok(result)
    }
}

impl<T: ?Sized> BloomFilter<T> {
    /// 创建两个布隆过滤器的并集，新过滤器的位数组是两个输入过滤器按位或的结果
    ///
    /// # 参数
    /// - `filter1`: 第一个布隆过滤器引用
    /// - `filter2`: 第二个布隆过滤器引用
    ///
    /// # 返回值
    /// 返回 `Ok(Self)` 表示合并成功，返回 `Err` 表示配置不匹配或创建失败
    pub fn union(filter1: &Self, filter2: &Self) -> Result<Self, &'static str> {
        if filter1.table_size != filter2.table_size
            || filter1.num_functions != filter2.num_functions
            || filter1.hash_func != filter2.hash_func
        {
            return Err("Filter configurations mismatch");
        }

        let mut result = BloomFilter::new(
            filter1.table_size,
            filter1.hash_func,
            filter1.num_functions,
        )?;

        result.table.iter_mut()
            .zip(filter1.table.iter().zip(filter2.table.iter()))
            .for_each(|(dst, (a, b))| *dst = *a | *b);

        Ok(result)
    }
}